package com.example.takeaways.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.takeaways.common.BaseContext;
import com.example.takeaways.common.R;
import com.example.takeaways.dto.OrdersDto;
import com.example.takeaways.entity.OrderDetail;
import com.example.takeaways.entity.Orders;
import com.example.takeaways.service.OrderDetailService;
import com.example.takeaways.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    private OrderService orderService;


    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @PutMapping()
    public R<String> updateOrderStatus(@RequestBody Map<String, Object> payload) {
        try {
            Long id = Long.valueOf((String) payload.get("id"));
            Integer status = (Integer) payload.get("status");

            Orders orders = orderService.getById(id);
            if (Objects.isNull(orders)) {
                return R.error("订单不存在，ID: " + id);
            }

            orders.setStatus(status);
            boolean updateSuccess = orderService.updateById(orders);

            if (updateSuccess) {
                return R.success("订单状态更新成功");
            } else {
                return R.error("订单状态更新失败，ID: " + id);
            }
        } catch (NumberFormatException e) {
            return R.error("ID或状态值格式不正确");
        } catch (ClassCastException e) {
            return R.error("请求负载格式不正确");
        }
    }

    @PostMapping("/submit2")
    public R submit2(@RequestBody Orders orders){

        orderService.submit2(orders);
        return R.success("下单成功");
    }

    /**
     * 下单明细
     *
     * @param page
     * @param pageSize
     * @param number
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(number), Orders::getNumber, number);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }


    @GetMapping("/userPage")
    public R<Page> userPage(int page,int pageSize){
        // 新创返回类型Page
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        // 用户ID
        Long currentId = BaseContext.getCurrentId();
        // 原条件写入
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,currentId);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo,queryWrapper);
        // 普通赋值
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");
        // 订单赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            // 新创内部元素
            OrdersDto ordersDto = new OrdersDto();
            // 普通值赋值
            BeanUtils.copyProperties(item,ordersDto);
            // 菜单详情赋值
            Long itemId = item.getId();
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,itemId);

            List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        // 完成dishDtoPage的results的内容封装
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }
}
